import React from 'react';
import axios from "axios";
import EChartsComponent from './EChartsComponent';

export default class Echarts extends React.Component {
  state = {
    chartOption: {
      title: { text: '正在加载数据...' },
      tooltip: {},
      legend: { data: ['销量', '月销售额'] },
      xAxis: { data: [] },
      yAxis: {},
      series: []
    }
  };

  componentDidMount(){
      axios.get('http://localhost:3000/api1/productSales')
          .then((response)=> {
            const backendData = response.data.data;
            // 前端转换数据格式
                 const newOption = {
                    title: { 
                      text: '商品销售数量'
                    },
                    tooltip: {},
                    xAxis: { 
                      type: 'category',
                      data: backendData.map(item => item.category)
                    },
                    yAxis: {},
                    series: [{
                      name: '销量',
                      type: 'bar',
                      data: backendData.map(item => item.sales_volume)
                    }]
                  };
            // 将数据存入 state
            this.setState({
              chartOption: newOption,
            });
          })
          .catch(error => {
            console.error('请求失败:', error);
          });
  }
  render() {
    return (
      <div>
        <h1>类式组件中使用ECharts示例</h1>
        <EChartsComponent option={this.state.chartOption} />
      </div>
    )
  }
}
